<!--
 * @Author: 睡衣船长 121771372@qq.com
 * @Date: 2023-10-09 17:15:21
 * @LastEditors: Mr.wangxf 2712638312@qq.com
 * @LastEditTime: 2023-11-14 19:09:33
 * @Description:
-->

<template>
  <div class="task-detail">
    <xr-dialog
      ref="taskDetailDialogRef"
      v-bind="taskDetailDialog"
      v-model="taskDetailDialogVisible"
      @complete-click="onCloseDialog"
    >
      <template #body>
        <div class="top flex-between-center">
          <div class="title_head" @click="taskNameInputFocus">
            <div class="title flex-left-center pointer">
              <el-input
                ref="taskNameRef"
                class="task-name"
                v-model="taskDetail.taskName"
                @blur="updateTaskName"
                :disabled="!canManage || taskDetail.status == 3"
                :maxLength="taskDetail.parentId == 0 ? 20 : 20"
              >
                <template v-slot:prefix>
                  {{ taskDetail.taskName }}
                </template>
              </el-input>
              <div class="flex pen pointer" v-if="taskDetail.status != 3">
                <img :src="_getImg('task-name-edit-pen.png')" />
              </div>
            </div>
          </div>
          <div
            class="status flex pointer"
            :class="'status' + taskDetail.status"
            @click="updateTaskStatus"
          >
            <span v-if="taskDetail.status == 1"> 未开始 </span>
            <span v-if="taskDetail.status == 2"> 完成任务 </span>
            <span v-if="taskDetail.status == 3"> 已完成 </span>
          </div>
        </div>
        <div class="auto-tab">
          <!-- <auto-tab
            :tab-list="tabList"
            :cur-tab="curTab"
            @tab-item-change="
              (e: string) => {
                curTab = e;
              }
            "
          ></auto-tab> -->
        </div>
        <div
          class="form-list h-100 scrollClass overflow_auto"
          style="height: calc(100% - 120px)"
        >
          <!-- 基础信息 -->
          <div class="basic-info flex-left-top" v-if="curTab == 'taskInfo'">
            <div class="item flex-1" v-if="!isTemplate">
              <div
                class="sub-item flex-left-center"
                :class="taskDetail?.taskType == 2 ? 'pointer' : ''"
                @click="editStartTime"
              >
                <div class="label">计划时间</div>
                <div class="input" v-if="taskDetail.startTime">
                  {{ _formatDate(taskDetail.startTime, "yyyy-MM-dd") }} ~
                  {{ _formatDate(taskDetail.endTime, "yyyy-MM-dd") }}
                </div>
                <div class="input" v-else>
                  {{
                    taskDetail?.taskType == 2
                      ? "点击设置计划开始时间"
                      : "暂未设置"
                  }}
                </div>
              </div>
              <div class="sub-item flex-left-center">
                <div class="label">实际时间</div>
                <div class="input" v-if="taskDetail.actualStartTime">
                  {{ _formatDate(taskDetail.actualStartTime, "yyyy-MM-dd") }} ~
                  {{
                    _formatDate(taskDetail.actualEndTime, "yyyy-MM-dd") ||
                    "未结束"
                  }}
                </div>
                <div class="input" v-else>未开始</div>
              </div>
            </div>
            <div class="item flex-1" v-if="taskDetail.parentId == 0">
              <div
                class="sub-item flex-left-center pointer"
                @click="editTaskDay"
              >
                <div class="label">持续时长</div>
                <div class="input">{{ taskDetail.taskDay || 0 }}天</div>
              </div>
              <div
                class="sub-item flex-left-center"
                :class="taskDetail?.taskType != 2 ? 'pointer' : ''"
                @click="editIntervalTime"
              >
                <div class="label">
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="与上个任务的间隔时长"
                    placement="top-start"
                  >
                    间隔时长
                  </el-tooltip>
                </div>
                <div class="input">
                  {{ taskDetail.intervalTime || 0 }}
                </div>
              </div>
            </div>
            <div class="item flex-1">
              <div class="sub-item flex-left-center" @click="editOrganization">
                <div class="label">部门</div>
                <div class="input">
                  {{
                    taskDetail.organizationType == 3
                      ? "门店"
                      : taskDetail.organizationType == 4
                        ? "施工队"
                        : taskDetail.orgName || "点击选择部门"
                  }}
                </div>
              </div>
              <div class="sub-item flex-left-center" @click="editExecutor">
                <div class="label">执行人</div>
                <div class="input">
                  {{
                    taskDetail.organizationType == 3
                      ? projectDetail.store.storeName
                      : taskDetail.organizationType == 4
                        ? "施工队"
                        : taskDetail.executorName || "点击选择执行人"
                  }}
                </div>
              </div>
            </div>
            <div class="item flex-1">
              <div
                class="sub-item flex-left-center"
                :class="taskDetail.status != 3 ? 'pointer' : ''"
                v-if="taskDetail.parentId == 0"
                @click="editRepeatType"
              >
                <div class="label">重复设置</div>
                <div class="input">
                  <span v-if="taskDetail.repeatType == 1">不重复</span>
                  <span v-if="taskDetail.repeatType == 2">每天重复</span>
                  <span v-if="taskDetail.repeatType == 3">每周重复</span>
                  <span v-if="taskDetail.repeatType == 4">每月重复</span>
                  <span v-if="taskDetail.repeatType == 5">工作日重复</span>
                </div>
              </div>
              <div
                class="sub-item flex-left-center"
                :class="taskDetail.status != 3 ? 'pointer' : ''"
                @click="editRemindRule"
              >
                <div class="label">提醒设置</div>
                <div class="input">
                  <span v-if="remindRule == 0">不提醒</span>
                  <span v-if="remindRule == 1">任务开始时</span>
                  <span v-if="remindRule == 2">任务开始前1天</span>
                  <span v-if="remindRule == 3">任务截止时</span>
                  <span v-if="remindRule == 4">任务截止前1天</span>
                </div>
              </div>
            </div>
          </div>
          <!-- 任务描述 -->
          <div class="taskDesc" v-if="curTab == 'taskInfo'">
            <div class="flex-left-center title">
              任务描述（{{ taskDetail?.taskDescription?.length || 0 }}/1000）
              <img
                v-if="taskDetail.status != 3 && canManage"
                class="pointer"
                :src="_getImg('task-name-edit-pen.png')"
                @click="editTaskDesc"
              />
            </div>
            <template v-if="!isCanEditTaskDesc">
              <!-- <xr-input
                class="taskDescText"
                type="textarea"
                v-if="taskDetail.taskDescription"
                v-model="taskDetail.taskDescription"
                :disabled="true"
              ></xr-input> -->
              <!-- <div class="taskDescText" v-else>无</div> -->
            </template>
            <!-- <xr-input
              v-else
              ref="taskDescRef"
              class="taskDescText"
              v-model="taskDetail.taskDescription"
              type="textarea"
              placeholder="请输入任务描述"
              :maxlength="1000"
            ></xr-input> -->
            <!-- :showWordLimit="true" -->
            <div
              class="flex-right-center"
              style="margin-top: 10px"
              v-if="isCanEditTaskDesc"
            >
              <!-- <xr-button
                class="btn reset"
                theme="miniSmall-default"
                @click="
                  isCanEditTaskDesc = false;
                  taskDetail.taskDescription = tempTaskDescription;
                "
                >取消</xr-button
              >
              <xr-button
                class="btn"
                theme="miniSmall-green"
                @click="
                  updateTaskDetail();
                  isCanEditTaskDesc = false;
                  tempTaskDescription = taskDetail.taskDescription;
                "
                >保存</xr-button
              > -->
            </div>
          </div>
          <!-- 关联表单 -->
          <div
            class="relative-form-add flex-left-center"
            v-if="curTab == 'taskInfo'"
          >
            <div class="flex pointer" @click="addRelativeForm">
              <img :src="_getImg('gap-menu-add-icon.png')" />
              关联表单
            </div>
          </div>
          <div class="taskDetailSplitLine" v-if="curTab == 'taskInfo'"></div>
          <div
            class="flex-left-top"
            style="width: 800px"
            v-for="(item, index) in taskDetail?.relativeItemList"
            :key="index"
          >
            <div class="detailLeft taskItems" v-if="curTab == 'taskInfo'">
              <div class="formListTitle">
                <div class="guidancePoints"></div>
              </div>
            </div>
            <div class="detailRight taskItems haveLine">
              <div
                class="formListTitle pointer flex-left-center"
                v-if="curTab == 'taskInfo'"
              >
                <!-- <tabItem
                  v-bind="{
                    title: item?.formModel?.title || ' ',
                    type: 'formId_' + item?.formModel?.id || '',
                  }"
                >
                </tabItem> -->
                <img
                  class="arrowIcon pointer"
                  :src="_getImg('down-arrow.png')"
                />
              </div>
              <div
                class="form-list-box"
                v-if="
                  curTab == 'taskInfo' ||
                  curTab == 'formId_' + item.formModel.id
                "
              >
                <el-skeleton
                  :rows="item.formModel?.fieldJsonList?.length || 10"
                  animated
                  v-if="loading"
                />

                <!-- <xr-form-list
                  v-else
                  :form-list="buildFormList(item.formModel).formList"
                  @formItemChange="formItemChange($event, item.formModel.id)"
                  :rules="buildFormList(item.formModel).formList"
                  :modelValue="buildFormList(item.formModel).formData"
                >
                </xr-form-list> -->
              </div>
            </div>
          </div>
          <!-- 子任务 -->
          <template v-if="curTab === 'taskInfo' || curTab === 'childTask'">
            <div
              class="flex-left-top"
              v-if="
                taskDetail.parentId == 0 ||
                (taskDetail.subTaskList && taskDetail.subTaskList.length > 0)
              "
            >
              <div class="detailLeft" v-if="curTab === 'taskInfo'">
                <div class="formListTitle">
                  <div class="guidancePoints"></div>
                </div>
              </div>
              <div class="detailRight">
                <div
                  class="taskDetailSplitLine"
                  v-if="curTab === 'taskInfo'"
                ></div>
                <div
                  class="formListTitle pointer flex-left-center"
                  v-if="curTab === 'taskInfo'"
                  @click="subTaskListVisible = !subTaskListVisible"
                >
                  <!-- <tabItem
                    v-bind="tabList.find((tab) => tab.type === 'childTask')"
                  ></tabItem> -->
                  <img
                    class="arrowIcon pointer"
                    :class="{ active: subTaskListVisible }"
                    :src="_getImg('down-arrow.png')"
                  />
                </div>
                <div
                  class="form-list_relation-child-item"
                  v-if="subTaskListVisible"
                >
                  <div class="child-task-list w-100">
                    <!-- <sub-task-list
                      :is-template="props.isTemplate"
                      :parent-task="taskDetail"
                      @add-child-task="refreshTaskDetail"
                      @showChildDetailDialog="onShowChildDetailDialog"
                    ></sub-task-list> -->
                  </div>
                </div>
              </div>
            </div>
          </template>
          <!-- 验收人 -->
          <template v-if="curTab === 'accepted'">
            <!-- <GapAccepted
              v-bind="{ ...props, isTemplate, canManage, newTaskDetailFormList, acceptedUserList, manageUserId, isCanEdit }"
              @transformSet="formItemChange({ prop: 'need_acceptance', data: $event })"
              @refreshAcceptedList="refreshAcceptedListHandel"
            ></GapAccepted> -->
            <!-- <accept-list
              :id="taskDetail?.id"
              :task-detail="taskDetail"
              :is-template="props.isTemplate"
              @refreshAcceptedList="refreshTaskDetail"
              @transformSet="updateNeedAccept"
            ></accept-list> -->
          </template>
          <!-- 协作者 -->
          <template v-if="curTab === 'collaborate'">
            <!-- <collaborator
              ref="collaboratorRef"
              :id="taskDetail?.id"
              :status="taskDetail?.status"
              :executor="taskDetail?.executor"
              :project-id="taskDetail?.projectId || 0"
              :table-id="taskDetail?.tableId || 0"
              @refreshCollaborator="getCollaboratorList"
              :is-template="props.isTemplate"
            ></collaborator> -->
          </template>
          <!-- 依赖关系 -->
          <template v-if="curTab === 'dependent'">
            <div
              class="taskRelyon"
              v-if="
                taskDetail.parentId == 0 &&
                (taskDetail?.afterTaskList?.length || 0) +
                  (taskDetail?.beforeTaskList?.length || 0) >
                  0
              "
            >
              <div
                class="flex-between-center title cursor font-weight-500"
                @click="
                  (taskDetail?.afterTaskList?.length || 0) +
                    (taskDetail?.beforeTaskList?.length || 0) >
                  0
                    ? (task_rely_visible = !task_rely_visible)
                    : ''
                "
              >
                <div class="h-100 flex-left-center">
                  <img
                    class="title-front-icon"
                    :src="_getImg('gapFlowRelyOnIcon.png')"
                  />
                  <span class="title-font">
                    该任务有
                    {{
                      (taskDetail?.afterTaskList?.length || 0) +
                      (taskDetail?.beforeTaskList?.length || 0)
                    }}
                    条依赖关系
                  </span>
                </div>
                <div
                  :class="`transition-1ms ${
                    task_rely_visible ? 'jt-up' : 'jt-down'
                  }`"
                ></div>
              </div>
              <div
                class="con scrollClass"
                v-if="
                  task_rely_visible &&
                  (taskDetail?.afterTaskList?.length || 0) +
                    (taskDetail?.beforeTaskList?.length || 0)
                "
              >
                <template
                  v-if="
                    taskDetail.beforeTaskList &&
                    taskDetail.beforeTaskList.length > 0
                  "
                >
                  <div class="beforeTaskListTitle">
                    <span class="font-weight-500">前置任务</span>
                    <span>完成后开始当前任务</span>
                  </div>
                  <div
                    class="taskList cursor"
                    :style="
                      i == taskDetail.beforeTaskList.length - 1
                        ? 'margin-bottom: 0px'
                        : ''
                    "
                    v-for="(item, i) in taskDetail.beforeTaskList"
                    :key="i"
                    @click="toOtherTask(item.taskId)"
                  >
                    <div>
                      <span :class="'status' + item.status">
                        <template v-if="item.status == 0">未设置</template>
                        <template v-if="item.status == 1">未开始</template>
                        <template v-if="item.status == 2">进行中</template>
                        <template v-if="item.status == 3">已完成</template>
                        <template v-if="item.status == 4">逾期</template>
                      </span>
                      <span class="font-weight-500 item-task-name">{{
                        item.taskName
                      }}</span>
                    </div>
                  </div>
                </template>
                <template
                  v-if="
                    taskDetail.afterTaskList &&
                    taskDetail.afterTaskList.length > 0
                  "
                >
                  <div class="afterTaskListTitle">
                    <span class="font-weight-500">后置任务</span>
                    <span>当前任务完成后才开始</span>
                  </div>
                  <div
                    class="taskList cursor"
                    v-for="(item, i) in taskDetail.afterTaskList"
                    :key="i"
                    @click="toOtherTask(item.taskId)"
                  >
                    <div>
                      <span :class="'status' + item.status">
                        <template v-if="item.status == 0">未设置</template>
                        <template v-if="item.status == 1">未开始</template>
                        <template v-if="item.status == 2">进行中</template>
                        <template v-if="item.status == 3">已完成</template>
                        <template v-if="item.status == 4">逾期</template>
                      </span>
                      <span class="font-weight-500 item-task-name">{{
                        item.taskName
                      }}</span>
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </template>
          <!-- 费用管理 -->
          <template v-if="curTab === 'cost'">
            <!-- <cost-list
              :task-detail="taskDetail"
              :is-template="props.isTemplate"
            ></cost-list> -->
          </template>
        </div>
      </template>
    </xr-dialog>
    <!-- 表单列表弹窗页面 -->
    <!-- <select-form-list-dialog
      ref="selectFormListDialogRef"
      @updateSelectFormList="updateSelectFormList"
    ></select-form-list-dialog> -->
    <xr-dialog
      ref="singleItemDialogRef"
      v-bind="singleItemDialog"
      v-model="singleItemDialogVisible"
      @confirm-click="singleItemConfirm"
    >
      <template #body>
        <div class="single-input flex">
          <!-- <xr-input
            v-model="singleItemValue"
            type="number"
            v-if="singleProps == 'intervalTime' || singleProps == 'taskDay'"
          ></xr-input>
          <xr-date
            v-model="singleItemValue"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            v-if="singleProps == 'startTime'"
          ></xr-date>
          <xr-cascader
            v-if="singleProps == 'organizationId'"
            v-model="orgIdsList"
            placeholder="选择任务部门"
            :options="orgList"
            @change="onOrgChange"
            :props="orgProps"
          >
          </xr-cascader>
          <xr-select
            v-if="singleProps == 'executorId'"
            ref="executorRef"
            :requestFun="getUserList"
            placeholder="请选择执行人"
            v-model="singleItemValue"
          ></xr-select>
          <xr-select
            v-if="singleProps == 'repeatType'"
            ref="repeatTypeRef"
            :requestFun="repeatTypeList"
            placeholder="请选择重复类型"
            v-model="singleItemValue"
          ></xr-select>
          <xr-select
            v-if="singleProps == 'remindRule'"
            ref="remindRuleRef"
            :requestFun="remindRuleList_static"
            placeholder="请选择提醒规则"
            v-model="singleItemValue"
          ></xr-select> -->
        </div>
      </template>
    </xr-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick, computed, inject } from "vue";
import { _deepClone, _formatDate, _getImg, _canObject } from "../utils/utils";
import xrDialog from "./dialog.vue";
// import {
//   apiGetTemplateTaskDetail,
//   apiGetTaskDetail,
//   apiUpdateTemplateTaskRelativeItem,
//   apiUpdateTaskRelativeItem,
//   apiGetRelativeItemList,
//   apiUpdateTask,
//   apiUpdateTemplateTask,
//   apiUpdateTaskStatus,
//   apiUpdateTaskForm,
//   apiGetAssistList,
//   apiGetRemindRuleList,
//   apiSubmitRemindRule,
//   apiUpdateRemindRule,
//   apiRemoveRemindRule,
// } from "@/api/raiseShop/task";
// import { fetchShopManageDet } from "@/api/raiseShop/shopManageDetails";
// import SubTaskList from "../SubTaskList/index.vue";
// import { fetchOrgUserList } from "@/api/departmentManage/orgUser";
// import { useOrgStore } from "@/pinia/org";
// import Collaborator from "./Collaborator.vue";
// import AcceptList from "./AcceptList.vue";
// import CostList from "./CostList.vue";

const props = defineProps({
  id: {
    type: String,
    default: "",
  },
  isTemplate: {
    type: Boolean,
    default: true,
  },
});

const projectDetail: any = inject("projectDetail", ref()); // 项目详情

const taskDetailDialog = ref({
  title: "门店名称",
  unScroll: false,
  checkCancel: true,
  centerStyle: "padding:10px 20px;",
  contentStyle: "height:700px;width:1200px;",
});

const taskDetailDialogVisible = ref(false);

const taskDetailDialogRef = ref();

const loading = ref(true);

const show = async () => {
  taskDetailDialogVisible.value = true;
  loading.value = true;
  // await refreshTaskDetail();
  // makeNewTabList();
  // projectDetail.value = await getProjectDetail()
  if (projectDetail.value?.prepareStoreName) {
    taskDetailDialog.value.title = projectDetail.value.prepareStoreName;
  }
  loading.value = false;
  console.log(taskDetail.value, "taskDetail", projectDetail.value);
};

const refreshTaskDetail = async () => {
  taskDetail.value = await getTaskDetail();
  remindRuleList.value = await getRemindRuleList();
};

const remindRuleList = ref([]);

const getRemindRuleList = async () => {
  if (!props.id) return [];
  return await apiGetRemindRuleList({ bizId: props.id, bizType: 4 });
};

const makeNewTabList = () => {
  tabList.value = _deepClone(old_tabList);
  const formList: any = [];
  taskDetail.value?.relativeItemList?.forEach((item: any) => {
    formList.push({
      title: item?.formModel?.title || " ",
      type: "formId_" + item.itemId,
    });
  });
  tabList.value.splice(1, 0, ...formList);
  console.log(tabList.value, "tabList");
};

const taskNameRef = ref();

// 点笔聚焦到taskName输入框
const taskNameInputFocus = () => {
  taskNameRef.value && taskNameRef.value.focus();
};

const taskDetail = ref<task.TaskTemplate>({});

const subTaskId = ref("");

const getTaskDetail = async () => {
  if (!props.id) return {};
  const id = subTaskId.value || props.id;
  return props.isTemplate
    ? await apiGetTemplateTaskDetail(id)
    : await apiGetTaskDetail(id);
};

const updateTaskName = () => {
  // props.taskDetail.taskName = taskName.value
  // _pageCtrl.updateTaskName(taskName.value)
  updateTaskDetail();
};

const canManage = true;

const old_tabList = [
  { title: "任务信息", type: "taskInfo" },
  { title: "子任务", type: "childTask" },
  { title: "验收人", type: "accepted" },
  { title: "协作者", type: "collaborate" },
  { title: "费用管理", type: "cost" },
  { title: "依赖关系", type: "dependent" },
];

const tabList = ref([]);

const curTab = ref("taskInfo");

// 获取项目详情
// async function getProjectDetail() {
//   if (!taskDetail.value.prepareStoreId) return {}
//   return await fetchShopManageDet({ id: Number(taskDetail.value.prepareStoreId) })
// }

// const projectDetail = ref() // 项目详情

const isCanEditTaskDesc = ref(false);

const tempTaskDescription = ref("");

const taskDescRef = ref();

const editTaskDesc = () => {
  isCanEditTaskDesc.value = true;
  taskDescRef.value?.inputRef?.focus();
};

const formItemChange = async (value: any, formId: Bus_StringNo) => {
  console.log(value, "formItemChange,value", formId);
  const fieldValue = taskDetail.value.fieldValue;
  fieldValue[formId][value.prop] = value.data;
  await apiUpdateTaskForm({ id: taskDetail.value.id, fieldValue });
  refreshTaskDetail();
  // updateTaskDetail()
};

const selectFormListDialogRef = ref({
  showDialog: () => {},
});

const addRelativeForm = () => {
  nextTick(() => {
    selectFormListDialogRef.value.showDialog();
  });
};

const updateSelectFormList = async (e: any) => {
  if (!taskDetail.value.id) return;
  let old_ids: any = [];
  let old_itemIds: any = [];
  taskDetail.value?.relativeItemList?.forEach((item: any) => {
    old_ids.push(item.id);
    old_itemIds.push(item.itemId);
  });
  let new_items: any = [];
  e.forEach((item: any) => {
    console.log(item, "item updateSelectFormList");
    let index = old_ids.indexOf(item.itemId);
    if (index > -1) {
      new_items.push({
        id: old_ids[index],
        itemId: item.id,
      });
    } else {
      new_items.push({
        itemId: item.id,
      });
    }
  });

  const params = {
    id: taskDetail.value.id,
    relativeItemList: new_items,
  };
  const res = props.isTemplate
    ? await apiUpdateTemplateTaskRelativeItem(params)
    : await apiUpdateTaskRelativeItem(params);
  console.log(res, "关联表单");
  getRelativeItemList();
  await refreshTaskDetail();
};

const getRelativeItemList = () => {
  apiGetRelativeItemList({ taskId: taskDetail.value.id }).then((res: any) => {
    console.log(res, "apiGetRelativeItemList");
    taskDetail.value.relativeItemList = res;
    makeNewTabList();
  });
};

const acceptedRefuseFieldList = ref([]);

const buildFormList = (formModel: any) => {
  if (!formModel.id) return {};
  //需要上传文件的prop
  let uploadPropArr: Array<string> = [];
  const arr = formModel?.fieldJsonList?.list || [];
  const fieldValue = taskDetail.value?.fieldValue[formModel.id];
  let formData: { [key: string]: any } = {};
  const formList: XrFormType.GapFormItemType[] = [];
  const formRules = {};
  //所有必填项的prop
  const requiredPropArr: Array<string> = [];
  arr?.forEach((item: any) => {
    //获取所有需要上传的prop
    if (
      item.typeName === "upload-picture" ||
      item.typeName === "upload-video" ||
      item.typeName === "upload-attach"
    ) {
      uploadPropArr.push(item.fieldIdentification);
    }
    //如果是上传的prop对数据进行处理
    if (
      uploadPropArr.includes(item.fieldIdentification) &&
      fieldValue &&
      fieldValue[item.fieldIdentification]?.length
    ) {
      // fieldValue[item.fieldIdentification] = JSON.parse(fieldValue[item.fieldIdentification])
    }
    if (
      uploadPropArr.includes(item.fieldIdentification) &&
      item.widgetProperty &&
      item.widgetProperty.defaultValue?.length
    ) {
      item.widgetProperty.defaultValue = JSON.parse(
        item.widgetProperty.defaultValue
      );
    }
    formData[item.fieldIdentification] = item.widgetProperty?.defaultValue;
    //处理下拉选择的options
    if (item.widgetProperty?.options) {
      item.widgetProperty.options.forEach((it: any) => {
        it.label = it.value;
        it.value = it.key;
      });
    }
    //处理formList数据
    formList.push({
      prop: item.fieldIdentification,
      type: item.typeName as
        | ""
        | "number"
        | "input"
        | "textarea"
        | "select"
        | "datetime"
        | "switch"
        | "select-multiple"
        | "upload-picture"
        | "upload-video"
        | "upload-attach"
        | "datePicker"
        | "staff"
        | "specialSelect"
        | "cascader",
      label: item.fieldName,
      options: item.widgetProperty?.options,
      placeholder: item.widgetProperty?.placeholder,
      canUploadMaxNum: 9,
      disabled: false, // TODO:权限控制，模板不需要填写
      maxlength:
        item.typeName === "input" || item.typeName === "number" ? 50 : 200,
      required: Boolean(item.rules && item.rules[0].required),
      showWordLimit: true,
    });

    //规则
    if (item.rules && item.rules[0].required) {
      requiredPropArr.push(item.fieldIdentification);
      formRules[item.fieldIdentification] = [
        {
          required: Boolean(item.rules[0].required),
          message: item.rules[0].message,
          trigger: "change",
        },
      ];
    }
  });
  formData = { ...formData, ...fieldValue };
  console.log(formData, formRules, formList, "buildFormList");
  return { formList, formRules, formData };
};

const subTaskListVisible = ref(true);

const updateTaskDetail = async () => {
  if (!taskDetail.value.id) return;
  const params: any = {
    id: taskDetail.value.id,
    organizationId: taskDetail.value.organizationId,
    organizationType: taskDetail.value.organizationType || 2,
    startTime: taskDetail.value.startTime,
    taskName: taskDetail.value.taskName,
    executorId: taskDetail.value.executorId,
    endTime: taskDetail.value.endTime,
    completeTime: taskDetail.value.completeTime,
    taskDescription: taskDetail.value.taskDescription,
    repeatType: taskDetail.value.repeatType,
    taskDay: taskDetail.value.taskDay,
    actualStartTime: taskDetail.value.actualStartTime,
    isNeedAcceptance: taskDetail.value.isNeedAcceptance,
    intervalTime: taskDetail.value.intervalTime,
  };
  if (props.isTemplate) {
    params.taskSource = taskDetail.value.taskSource;
  }
  const res = props.isTemplate
    ? await apiUpdateTemplateTask(params)
    : await apiUpdateTask(params);
  console.log(res, "updateTaskDetail");
  await refreshTaskDetail();
};

const singleItemDialog = reactive({
  title: "",
  unScroll: false,
  checkCancel: true,
  showFooter: true,
  centerStyle: "padding:30px 20px;",
  contentStyle: "height:200px;width:500px;",
});

const singleItemDialogRef = ref();

const singleItemDialogVisible = ref(false);

const singleItemValue = ref<Bus_StringNo>("");

const singleProps = ref("startTime");

const editStartTime = () => {
  if (taskDetail.value.taskType != 2) return;
  singleProps.value = "startTime";
  singleItemDialog.title = "请选择计划开始时间";
  singleItemValue.value = taskDetail.value.startTime;
  singleItemDialogVisible.value = true;
};

const editTaskDay = () => {
  singleProps.value = "taskDay";
  singleItemDialog.title = "请设置持续时长";
  singleItemValue.value = taskDetail.value.taskDay;
  singleItemDialogVisible.value = true;
};

const editIntervalTime = () => {
  if (taskDetail.value.taskType == 2) return;
  singleProps.value = "intervalTime";
  singleItemDialog.title = "请设置间隔时长";
  singleItemValue.value = taskDetail.value.intervalTime;
  singleItemDialogVisible.value = true;
};

const editRepeatType = () => {
  singleProps.value = "repeatType";
  singleItemDialog.title = "请设置重复类型";
  singleItemValue.value = taskDetail.value.repeatType;
  singleItemDialogVisible.value = true;
};

const repeatTypeList = [
  {
    label: "不重复",
    value: 1,
  },
  {
    label: "每天重复",
    value: 2,
  },
  {
    label: "每周重复",
    value: 3,
  },
  {
    label: "每月重复",
    value: 4,
  },
  {
    label: "工作日重复",
    value: 5,
  },
];

const orgList = ref([]);

const orgIdsList = ref();

const orgProps = {
  checkStrictly: true,
  children: "subOrgList",
  label: "orgName",
  value: "id",
};

const executorRef = ref();

const onOrgChange = () => {
  singleItemValue.value = orgIdsList.value[orgIdsList.value.length - 1] || "";
  console.log(orgIdsList.value, "选择部门变化");
};

const getUserList = async () => {
  if (!taskDetail.value.organizationId) return [];
  const res: any = await fetchOrgUserList({
    orgId: taskDetail.value.organizationId,
  });
  console.log(res, "getUserList");
  if (!_canObject(res) && !res?.length) return [];
  const userList = res.map((tableUserItem: any) => {
    return {
      label: tableUserItem.user.nickName,
      value: tableUserItem.user.id + "",
    };
  });
  console.log(userList, "userList");
  return Promise.resolve(userList);
};

const editOrganization = () => {
  // useOrgStore()
  //   .getOrgList()
  //   .then((res: any) => {
  //     orgList.value = _deepClone(res);
  //     orgList.value.unshift({
  //       orgName: "门店",
  //       orgType: 3,
  //       id: "-1",
  //     });
  //     orgList.value.unshift({
  //       orgName: "施工队",
  //       orgType: 4,
  //       id: "-2",
  //     });
  //     singleProps.value = "organizationId";
  //     singleItemDialog.title = "请选择部门";
  //     if (taskDetail.value.organizationType == 3) {
  //       singleItemValue.value = "-1";
  //     } else if (taskDetail.value.organizationType == 4) {
  //       singleItemValue.value = "-2";
  //     } else {
  //       singleItemValue.value = taskDetail.value.organizationId;
  //     }
  //     orgIdsList.value = singleItemValue.value.toString();
  //     singleItemDialogVisible.value = true;
  //   });
};
// TODO
const editExecutor = () => {
  if (
    !!taskDetail.value.organizationType &&
    taskDetail.value.organizationType == 4
  ) {
    return false;
  }
  if (
    !!taskDetail.value.organizationType &&
    taskDetail.value.organizationType == 3
  ) {
    // _$notifyFun({ con: '门店', type: 'warning' })
    return false;
  }

  singleProps.value = "executorId";
  singleItemDialog.title = "请选择执行人";
  singleItemValue.value = taskDetail.value.executorId;
  singleItemDialogVisible.value = true;
  nextTick(() => {
    executorRef.value.getOptionList();
  });
};

const remindRule = computed(() => {
  if (remindRuleList.value?.length <= 0) {
    return 0;
  } else {
    const remindRule_new =
      remindRuleList.value[remindRuleList.value.length - 1];
    if (remindRule_new.remindType == 1) return 1;
    if (remindRule_new.remindType == 2 && remindRule_new.value == 1) return 2;
    if (remindRule_new.remindType == 3) return 3;
    if (remindRule_new.remindType == 4 && remindRule_new.value == 1) return 4;
    return 0;
  }
});

const remindRuleList_static = [
  {
    label: "不提醒",
    value: 0,
  },
  {
    label: "任务开始时",
    value: 1,
  },
  {
    label: "任务开始前1天",
    value: 2,
  },
  {
    label: "任务截止时",
    value: 3,
  },
  {
    label: "任务截止前1天",
    value: 4,
  },
];

const editRemindRule = () => {
  singleProps.value = "remindRule";
  singleItemDialog.title = "请设置提醒规则";
  singleItemValue.value = remindRule.value;
  singleItemDialogVisible.value = true;
};

const updateRemindRule = async (value: Bus_StringNo) => {
  const params: any = {
    bizId: props.id,
    bizType: props.isTemplate ? 2 : 4,
    remindType: 0,
    value: 0,
  };
  switch (value) {
    case 0:
      if (remindRuleList.value.length > 0) {
        const remove_id =
          remindRuleList.value[remindRuleList.value.length - 1].id;
        await apiRemoveRemindRule({ ids: remove_id });
      }
      break;
    case 1:
      params.remindType = 1;
      params.value = 0;
      if (remindRuleList.value.length > 0) {
        params.id = remindRuleList.value[remindRuleList.value.length - 1].id;
        await apiUpdateRemindRule(params);
      } else {
        await apiSubmitRemindRule(params);
      }
      break;
    case 2:
      params.remindType = 2;
      params.value = 1;
      if (remindRuleList.value.length > 0) {
        params.id = remindRuleList.value[remindRuleList.value.length - 1].id;
        await apiUpdateRemindRule(params);
      } else {
        await apiSubmitRemindRule(params);
      }
      break;
    case 3:
      params.remindType = 3;
      params.value = 0;
      if (remindRuleList.value.length > 0) {
        params.id = remindRuleList.value[remindRuleList.value.length - 1].id;
        await apiUpdateRemindRule(params);
      } else {
        await apiSubmitRemindRule(params);
      }
      break;
    case 4:
      params.remindType = 4;
      params.value = 1;
      if (remindRuleList.value.length > 0) {
        params.id = remindRuleList.value[remindRuleList.value.length - 1].id;
        await apiUpdateRemindRule(params);
      } else {
        await apiSubmitRemindRule(params);
      }
      break;
    default:
      break;
  }
  await refreshTaskDetail();
};

const singleItemConfirm = () => {
  if (
    singleProps.value == "organizationId" &&
    taskDetail.value.organizationId != singleItemValue.value
  ) {
    taskDetail.value.executorId = "";
    taskDetail.value.executorName = "";
    if (singleItemValue.value == "-1") {
      taskDetail.value.organizationType = 3;
      if (!props.isTemplate && projectDetail.value) {
        singleItemValue.value = projectDetail.value.store.id;
        taskDetail.value.executorId = projectDetail.value.store.id;
      }
    } else if (singleItemValue.value == "-2") {
      taskDetail.value.organizationType = 4;
      if (!props.isTemplate && projectDetail.value) {
        singleItemValue.value = projectDetail.value?.constructionTeamId
          ? projectDetail.value.constructionTeamId
          : null;
        taskDetail.value.executorId = projectDetail.value?.constructionTeamId
          ? projectDetail.value.constructionTeamId
          : null;
      }
    } else {
      taskDetail.value.organizationType = 2;
    }
  }
  if (singleProps.value == "remindRule") {
    updateRemindRule(singleItemValue.value);
  } else {
    taskDetail.value[singleProps.value] = singleItemValue.value;
    updateTaskDetail();
  }
};

const updateNeedAccept = (isNeed: boolean) => {
  console.log(isNeed, "isNeed");
  taskDetail.value.isNeedAcceptance = Number(isNeed);
  updateTaskDetail();
};

const updateTaskStatus = () => {
  if (taskDetail.value.status != 2) return;
  apiUpdateTaskStatus({
    id: taskDetail.value.id,
    status: 3,
  }).then(async () => {
    await refreshTaskDetail();
  });
};

const collaboratorList = ref([]);

const collaboratorRef = ref();

const getCollaboratorList = () => {
  if (!taskDetail.value.id) {
    return;
  }
  apiGetAssistList({ taskId: Number(taskDetail.value.id) }).then((res: any) => {
    console.log(res, "获取的协作者列表");
    collaboratorList.value = res;
    collaboratorRef.value?.getList(res);
  });
};

const task_rely_visible = ref(false);

const toOtherTask = (value: any) => {
  console.log(value, "toOtherTask");
};

const emit = defineEmits<{
  (e: "onClose", data: any): void;
}>();

const onShowChildDetailDialog = (value: any) => {
  console.log(value, "subTaskDetail");
  subTaskId.value = value.id;
  refreshTaskDetail();
};

const onCloseDialog = () => {
  if (subTaskId.value) {
    subTaskId.value = "";
    console.log("重新打开");
    nextTick(async () => {
      await show();
    });
  } else {
    emit("onClose", { taskDetail: taskDetail.value, id: props.id });
    initFun();
  }
};

const initFun = () => {
  remindRuleList.value = [];
  taskDetail.value = {};
  curTab.value = "taskInfo";
};

defineExpose({
  show,
});
</script>

<style lang="scss" scoped>
@import "./xr-theme.scss";

.top {
  .status {
    width: 100px;
    height: 30px;
    font-size: 16px;
    color: #009ef7;
    border: 1px solid #009ef7;
    border-radius: 4px;
    display: flex;
    line-height: 30px;

    &.status1 {
      color: #5e6278;
      border: 1px solid #5e6278;
    }

    &.status2 {
      color: #009ef7;
      border: 1px solid #009ef7;
    }

    &.status3 {
      color: #04c8c8;
      border: 1px solid #04c8c8;
    }
  }
}

.title_head {
  width: 100%;
  border-bottom: 1px solid transparent;

  .title {
    width: 100%;

    :deep(.el-input) {
      width: auto;
      flex: 0;

      &:focus-within {
        flex: 1;
      }
    }

    :deep(.el-input__wrapper),
    :deep(.el-input__inner) {
      padding: 0;
      font-size: 20px;
      background-color: none;
      box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color))
        inset;
      border-radius: 8px;
      border: 1px solid #fff;
      font-size: 20px;
      font-weight: 500;
      color: #181c32;

      &.is-focus {
        background-color: none;
        border: 1px solid var(--el-input-border-color, var(--el-border-color));
      }
    }

    :deep(.is-focus) {
      width: 100% !important;
      border: 1px solid transparent !important;
    }

    :deep(.el-input__prefix) {
      display: inline-block;
      position: relative;
      border: 1px solid #dcdfe6;
      height: 40px;
      line-height: 40px;
      transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
      left: 0;
      visibility: hidden;
    }

    :deep(.el-input__inner) {
      position: absolute;
    }

    .task-name {
      &.is-disabled {
        :deep(.el-input__wrapper) {
          background-color: #fff;
        }
      }
    }

    .pen {
      width: 16px;
      height: 16px;
      margin-left: 10px;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .title:focus-within {
    .pen {
      display: none;
    }
  }
}

.title_head:focus-within {
  border-bottom: 1px solid #e4e6ef;
}

.basic-info {
  padding-top: 20px;

  .sub-item {
    margin-bottom: 20px;
  }

  .label {
    width: 70px;
    text-align: left;
    font-weight: bold;
    color: #b5b5c3;
  }
}

.taskDesc {
  padding: 10px 0;

  .title {
    font-size: 14px;
    color: #5e6278;

    img {
      width: 16px;
      height: 16px;
      margin-left: 5px;
    }
  }

  .taskDescText {
    margin-top: 15px;
    min-height: 44px;

    :deep(.el-textarea) {
      &.is-disabled .el-textarea__inner {
        padding: 0;
        background: #fff;
        color: #3f4254;
        cursor: default;
        resize: none;
      }
    }

    &.active {
      :deep(.el-textarea__inner) {
        // background:#fff;
        color: #b5b5c3 !important;
      }
    }
  }
}

.relative-form-add {
  margin-top: 15px;
  color: #04c8c8;
  font-weight: 500;

  img {
    width: 16px;
    height: 16px;
    margin-right: 4px;
  }
}

.detailLeft {
  margin-right: 15px;

  .formListTitle {
    margin-top: 31px;
  }

  &.taskItems {
    .formListTitle {
      margin-top: 20px;
    }
  }
}

.detailRight {
  flex: 1;
  position: relative;

  &.haveLine::before {
    position: absolute;
    left: -22px;
    top: 44px;
    content: "";
    display: block;
    width: 1px;
    height: calc(100% - 13px);
    background: #eff2f5;
  }

  &.taskItems {
    &.haveLine::before {
      top: 33px;
      height: calc(100% - 2px);
    }
  }
}

.formListTitle {
  margin-top: 15px;

  .guidancePoints {
    width: 13px;
    height: 13px;
    border: 3px solid #009ef7;
    border-radius: 50%;
  }

  :deep(.tabListItem) {
    color: #000000;
    margin-right: 4px;

    .unNum {
      &.active {
        color: #000000;
      }
    }
  }

  .arrowIcon {
    width: 10px;
    height: 10px;

    &.active {
      transform: rotate(180deg);
    }
  }
}

.form-list {
  padding: 0 5px;
  margin-top: 15px;
  height: calc(100% - 100px);

  .taskDesc {
    padding: 10px 0;

    .title {
      font-size: 14px;
      color: #5e6278;

      img {
        width: 16px;
        height: 16px;
        margin-left: 5px;
      }
    }

    .taskDescText {
      margin-top: 15px;
      min-height: 44px;

      :deep(.el-textarea) {
        &.is-disabled .el-textarea__inner {
          padding: 0;
          background: #fff;
          color: #3f4254;
          cursor: default;
          resize: none;
        }
      }

      &.active {
        :deep(.el-textarea__inner) {
          // background:#fff;
          color: #b5b5c3 !important;
        }
      }
    }
  }

  .taskMainDetailBox {
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 8px;

    .detailItem {
      height: 40px;
      width: 100%;
      font-size: 14px;

      .label {
        flex-shrink: 0;
        width: 69px;
        color: #b5b5c3;

        &.width53 {
          width: 53px;
        }

        &.active {
          color: #009ef7;
        }
      }

      .itemValue {
        position: relative;
        color: #5e6278;
        cursor: pointer;

        &.disabled {
          cursor: not-allowed;
        }

        .durationNum {
          color: #181c32;
          margin-right: 3px;
          font-weight: 500;
        }

        img {
          flex-shrink: 0;
          width: 22px;
          height: 22px;
          margin-right: 15px;
        }

        &.red {
          color: $deleteColor;
        }

        &.blue {
          color: #009ef7;
        }

        &.green {
          color: $greenBtnBgColor;
        }

        :deep(.el-date-editor) {
          width: 80%;
          min-width: 125px;
        }

        :deep(.el-input__wrapper) {
          height: 32px;
          min-height: 32px;
          padding: 0;
          background: #fff;
          box-shadow: none;

          .el-input__inner {
            color: #3f4254;
          }

          .el-input__prefix {
            display: none;
          }
        }

        :deep(.el-cascader),
        :deep(.el-select) {
          .el-input__suffix-inner {
            .icon-arrow-down,
            .el-select__icon {
              display: none;
            }
          }
        }

        &:hover {
          :deep(.el-cascader),
          :deep(.el-select) {
            .el-input__suffix-inner {
              .icon-arrow-down,
              .el-select__icon {
                display: block;
              }
            }
          }
        }
      }

      &.active .itemValue {
        .placeholderText {
          width: 80%;
          color: #009ef7;
          position: absolute;
          top: 0;
          left: 0;
          line-height: 32px;
          pointer-events: none;
          background: #fff;
        }
      }

      .durationSetBox {
        width: 280px;
        height: 150px;
        border-radius: 16px;
        padding: 16px;

        .title {
          height: 22px;
          line-height: 22px;
          font-size: 14px;
          color: #3f4254;
        }

        .timeInput {
          width: 100%;
          margin-top: 8px;

          :deep(.el-input__wrapper) {
            background-color: #f5f8fa;
          }
        }

        .sure {
          margin-top: 16px;
          text-align: center;
          height: 36px;
          line-height: 36px;
          background-color: #04c8c8;
          color: white;
          border-radius: 8px;
          font-size: 14px;
        }
      }
    }
  }

  .form-list-box {
    padding-bottom: 10px;
  }

  .taskDetailSplitLine {
    width: 100%;
    margin: 10px 0;
    border-bottom: 1px dashed #eff2f5;
  }

  &-box {
    margin-bottom: 8px;
  }

  &_relation-child-item {
    .item-name {
      line-height: 22px;
      color: #3f4254;
    }

    .relationFormList {
      font-size: 14px;
      font-weight: 500;

      .listItem {
        padding: 11px 0;
        border-bottom: 1px dashed #eff2f5;

        .itemName {
          line-height: 22px;
          color: #009ef7;

          &.active {
            color: #3f4254;
          }
        }

        .itemValue {
          flex-shrink: 0;
          height: 22px;
        }

        .delIcon {
          width: 24px;
          height: 24px;
          margin-left: 12px;
        }

        .statusIcon {
          width: 20px;
          height: 20px;
          margin-right: 6px;
        }
      }

      .addRelativeForm {
        margin-top: 14px;
        font-size: 14px;
        font-weight: 500;
        color: $greenBtnBgColor;

        img {
          width: 16px;
          height: 16px;
          margin-right: 4px;
        }
      }
    }
  }

  :deep(.el-input__wrapper) {
    border-radius: 8px;
  }
}
</style>
